<script setup lang="ts">
/**
 * @see {@link https://vuejs.org/api/sfc-script-setup.html#defineoptions}
 */
defineOptions({
  name: "User",
  inheritAttrs: false,
});
import { ElMessage, ElMessageBox } from "element-plus";
import dayjs from "dayjs";
import sha256 from "sha256";
import {
  addUser,
  UserList,
  delUser,
  addFormUser,
  editUserPassword,
  editUserStatus,
  updateUserStatus,
  getRoleOptions,
  LibraryOptions,
} from "@/api/user";
import useUserStore from "@/store/modules/user";
import { onMounted, ref, reactive } from "vue";
const libraryaOpt = ref();
const libOptions = async () => {
  const { data } = await LibraryOptions(useStore.encryptedData);
  libraryaOpt.value = data;
  //console.log(data, "图书馆");
};
let useStore = useUserStore();
const userFormRef = ref(); // 用户表单
let RoleOptions = ref([] as any);
const loading = ref(false);
const ids = ref([]);
const total = ref(0);
let dialog = reactive({
  visible: false,
  title: "",
});
const isEditDialog = ref(false);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});
const userList = ref([{}] as any);

let formData = ref({
  status: 1,
  password: null,
} as any);

/**
 * 查询
 */
function getUserList() {
  loading.value = true;
  UserList(queryParams.value)
    .then((res) => {
      if (res.code == 200) {
        const updatedUserList = res.data.records.map((record: any) => {
          const timestamp = record.createTime; // 假设时间戳单位为秒
          const date = dayjs(timestamp);
          const formattedDate = date.format("YYYY/MM/DD HH:mm:ss"); // 使用 dayjs.format 方法转换为指定的日期时间格式

          record.createTime = formattedDate;

          return record;
        });
        userList.value = updatedUserList;
        total.value = res.data.total;
        // console.log(res.data, "data");
      }
    })
    .finally(() => {
      loading.value = false;
    });
}

const rules = reactive({
  expireTime: [
    { required: true, message: "请选择日期时间", trigger: "change" },
  ],
  libraryId: [{ required: true, message: "请选择图书馆", trigger: "change" }],
  isTempUser: [
    { required: true, message: "请选择用户类型", trigger: "change" },
  ],
  username: [
    {
      required: true,
      message: "用户名不能为空",
      trigger: "blur",
    },
    {
      required: true,
      message: "20位内小写字母",
      trigger: "blur",
      pattern: /^[a-z]{1,20}$/,
    },
  ],
  gender: [{ required: true, message: "性别不能为空", trigger: "change" }],
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  roleId: [{ required: true, message: "用户角色不能为空", trigger: "change" }],
  email: [
    {
      required: true,
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  mobile: [
    {
      required: true,
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

/**
 * 修改用户状态
 */
function handleStatusChange(row: { [key: string]: any }) {
  const text = row.status === 1 ? "启用" : "停用";
  ElMessageBox.confirm("确认要" + text + row.username + "用户吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      return editUserStatus({ id: row.id, status: row.status });
    })
    .then(() => {
      ElMessage.success(text + "成功");
    })
    .catch(() => {
      row.status = row.status === 1 ? 0 : 1;
    });
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 重置密码
 */
const resetPassword = (row: any) => {
  ElMessageBox.confirm("此操作将重置密码为11111111?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async function () {
      editUserPassword({ id: row.id, password: sha256("11111111") }).then(
        () => {
          ElMessage.success("密码重置成功，新密码是：" + "111111111");
        }
      );
    })
    .catch(() => {});
};

// function resetPassword(row: { [key: string]: any }) {
//   ElMessageBox.prompt(
//     "请输入用户「" + row.username + "」的新密码",
//     "重置密码",
//     {
//       confirmButtonText: "确定",
//       cancelButtonText: "取消",
//     }
//   )
//     .then(({ value }) => {
//       if (!value) {
//         ElMessage.warning("请输入新密码");
//         return false;
//       }
//       updateUserPassword(row.id, value).then(() => {
//         ElMessage.success("密码重置成功，新密码是：" + value);
//       });
//     })
//     .catch(() => {});
// }

/**
 * 打开弹窗
 *
 * @param userId 用户ID
 */
const roleIdsref = ref();
//const genderref = ref();
async function openDialog(userId?: number) {
  formData.value.roleId = "";
  if (isTempUserRef.value) {
    isTempUserRef.value.clearValidate();
  }

  // formData.value.genderref = [];
  if (userId) {
    const ress = await getRoleOptions(useStore.encryptedData);
    RoleOptions.value = ress.data;
    const res = await addFormUser(userId);
    formData.value = res.data;
    //console.log(res.data, "addFormUser");

    dialog.title = "修改用户";
    //  isEditDialog.value = true;
  } else {
    dialog.title = "新增用户";

    const res = await getRoleOptions(useStore.encryptedData);
    RoleOptions.value = res.data;
    if (roleIdsref.value) {
      roleIdsref.value.clearValidate();
    }
    // if (genderref.value) {
    //   genderref.value.clearValidate();
    // }
    // isEditDialog.value = false;
  }
  dialog.visible = true;
}

/**
 * 关闭用户弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
const isTempUserRef = ref();
function resetForm() {
  userFormRef.value.resetFields();
  userFormRef.value.clearValidate();
  roleIdsref.value.clearValidate();
  isTempUserRef.value.clearValidate();
  formData.value = {};
  formData.value.status = 1;
}

/**
 * 表单提交
 */
const handleSubmit = () => {
  userFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = formData.value.id;
      loading.value = true;
      if (userId) {
        // console.log(formData.value, "编辑");
        updateUserStatus(formData.value)
          .then((res) => {
            if (res.code === 200) {
              ElMessage.success("修改用户成功");
              closeDialog();

              getUserList();
            } else {
              // 如果响应码不是200，表示操作失败
              ElMessage.error(res.msg);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        //  console.log("新增");

        // addUser(formData.value)
        //   .then(() => {
        //     ElMessage.success("新增用户成功");
        //     closeDialog();

        //     getUserList();
        //   })
        //   .finally(() => (loading.value = false));

        formData.value.password = sha256("11111111");
        //console.log(formData.value);
        addUser(formData.value)
          .then((res) => {
            if (res.code === 200) {
              // 如果响应码是200，表示操作成功
              ElMessage.success("新增用户成功");
              closeDialog();
              getUserList();
            } else {
              // 如果响应码不是200，表示操作失败
              ElMessage.error(res.msg);
            }
          })
          .catch((error) => {
            // 处理可能发生的错误
            ElMessage.error("请求失败：" + error.message);
          })
          .finally(() => {
            loading.value = false; // 无论请求成功或失败，都停止加载动画
          });
      }
    }
  });
};
/**
 * 删除用户
 */
function handleDelete(id?: number) {
  const userIds = [id || ids.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除用户?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    //console.log(Number(userIds), userIds);

    delUser(userIds).then((res) => {
      if (res.code == 200) {
        ElMessage.success("删除成功");
        getUserList();
      }
    });
  });
}

onMounted(() => {
  getUserList(); // 初始化用户列表数据
  libOptions();
});
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;

  getUserList();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getUserList();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
const formatDateTime = () => {
  const formattedDateTime = dayjs(formData.value.expireTime).format(
    "YYYY-MM-DD HH:mm:ss"
  );
  formData.value.expireTime = formattedDateTime;
};
</script>

<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-card shadow="never">
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button type="success" @click="openDialog()"
                  ><el-icon><Plus /></el-icon>新增</el-button
                >
                <el-button
                  type="danger"
                  :disabled="ids.length === 0"
                  @click="handleDelete()"
                  ><el-icon><Delete /></el-icon>删除</el-button
                >
              </div>
            </div>
          </template>

          <el-table
            v-loading="loading"
            :data="userList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" align="center" />
            <el-table-column label="用户名" align="center" prop="username" />
            <el-table-column label="用户昵称" align="center" prop="nickname" />
            <el-table-column label="角色" align="center" prop="roleNames" />
            <el-table-column label="邮箱" align="center" prop="email" />
            <el-table-column label="手机号码" align="center" prop="mobile" />
            <el-table-column label="状态" align="center" prop="status">
              <template #default="scope">
                <el-switch
                  v-if="scope.row.status !== undefined"
                  v-model="scope.row.status"
                  :inactive-value="0"
                  :active-value="1"
                  @change="handleStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
            />
            <el-table-column
              label="操作"
              fixed="right"
              width="220"
              align="center"
            >
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="resetPassword(scope.row)"
                  icon="RefreshLeft"
                  >重置密码</el-button
                >
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="openDialog(scope.row.id)"
                  icon="Edit"
                  >编辑</el-button
                >
                <el-button
                  type="primary"
                  link
                  size="small"
                  icon="Delete"
                  @click="handleDelete(scope.row.id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <el-pagination
            style="margin-top: 15px"
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 30, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      append-to-body
      @close="closeDialog"
    >
      <el-form
        ref="userFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
        status-icon
      >
        <el-form-item label="过期时间" prop="expireTime" ref="expireTimeref">
          <el-date-picker
            v-model="formData.expireTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择时间"
            @change="formatDateTime"
          />
        </el-form-item>
        <el-form-item label="用户类型" prop="isTempUser" ref="isTempUserRef">
          <el-select
            v-model="formData.isTempUser"
            placeholder="用户类型"
            :disabled="isEditDialog"
          >
            <el-option label="长期用户" :value="0" />
            <el-option label="短期用户" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="图书馆"
          prop="libraryId"
          style="white-space: nowrap"
        >
          <el-select v-model="formData.libraryId" placeholder="请选择图书馆">
            <el-option
              v-for="item in libraryaOpt"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <!-- multiple -->
        <el-form-item label="角色" prop="roleId" ref="roleIdsref">
          <el-select
            v-model="formData.roleId"
            placeholder="请选择角色"
            :disabled="isEditDialog"
          >
            <el-option
              v-for="item in RoleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            maxlength="50"
          />
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            :readonly="!!formData.id"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
        </el-form-item>

        <el-form-item label="手机号码" prop="mobile">
          <el-input
            v-model="formData.mobile"
            placeholder="请输入手机号码"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
